%define NON_PAGING

%include "inc\support.inc"
%include "inc\portected.inc"
	
	bits 32
	org PROTECTED_SEG - 2

PROTECTED_BEGIN:
	protected_length dw PROTECTED_END - PROTECTED_BEGIN ;

entry:
	mov esi, GP_HANDLER_VECTOR
	mov edi, GP_handler
	call set_interrupt_handler

	mov esi, tss32_sel
	call get_tss_base
	mov DWORD [eax + 4], KERNAL_ESP

	call disable_8259

	mov esi, call_gate_sel
	mov edi, call_gate_hanlder
	mov eax, 0
	call set_call_gate

	;;  设置新的 TSS 区域
	mov esi, tss_sel
	call get_tss_base
	mov DWORD[eax + 32], tss_task_handler

	mov DWORD[eax + 36], 0
	mov DWORD[eax + 56], esp
	mov DWORD[eax + 76], cs
	mov DWORD[eax + 80], ss
	mov DWORD[eax + 84], ss
	mov DWORD[eax + 72], ss

	mov esi, tss_sel
	call read_gdt_descriptor
	or edx, 0x6000
	mov esi, tss_sel
	call write_gdt_descriptor

	mov esi, msg2
	call puts
	mov eax, CLIB32_GET_CPL
	call clib32_service_enter

	mov esi, eax
	call print_byte_value
	call println

	;;  通过 retf 实现到 ring3 的跳转
	;;  retf 会认为站定为 cs:eip
	push DWORD user_data32_sel | 0x3
	push esp
	push DWORD user_code32_sel | 0x3
	push DWORD user_entry
	retf

user_entry:
	;;  初始化段
	mov ax, user_data32_sel
	mov ds, ax
	mov es, ax

	;;  获得 CPL 值
	mov esi, msg2
	call puts
	mov eax, CLIB32_GET_CPL
	call clib32_service_enter
	mov esi, eax
	call print_byte_value
	call println

	call tss_sel:0
	mov esi, msg1
	call puts

	